<template>
  <div ref="foodRecipeRef" class="mobile-food-view common-mobile-view">
    <food-query />

    <div class="food-list">
      <el-empty v-if="foodStore.foodRecipeList.length === 0" description="暂无美食记录"/>

      <div v-else class="list">
        <food-card v-for="(item, index) in foodStore.foodRecipeList"
                   :key="index" :food-item="item"/>
      </div>
    </div>

    <arrive-bottom v-if="foodStore.isScrollEnd"/>
  </div>
</template>

<script lang="ts" setup>
import FoodQuery from '@/components/Food/FoodQuery.vue'
import FoodCard from '@/components/Food/FoodCard.vue'
import ArriveBottom from '@/components/Common/ArriveButton.vue'
import { useFoodStore } from '@/store/food.ts'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const foodRecipeRef = ref()
const foodStore = useFoodStore()

onMounted(async () => {
  foodStore.pageInfo = {
    currentPage: 1,
    pageSize: 3,
    totalSize: 1
  }
  foodStore.foodRecipeList = []
  await foodStore.queryMobileFoodRecipeList()
  foodRecipeRef.value.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  foodRecipeRef.value.removeEventListener('scroll', handleScroll)
})

const handleScroll = () => {
  const el = foodRecipeRef.value
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
    const { currentPage, pageSize, totalSize } = foodStore.pageInfo
    foodStore.isScrollEnd = pageSize * currentPage > totalSize
    if (!foodStore.isScrollEnd) {
      foodStore.pageInfo.currentPage++
      foodStore.queryMobileFoodRecipeList()
    }
  }
}
</script>

<style lang="scss">
@use "@/styles/home/food.mobile.module";
</style>
